package main

import (
	"net"
	"os"
	"fmt"
)

func do_response (con *net.TCPConn, response *string) {
	len, err := con.Write ([]byte (*response))
	if (len == 0 || err != nil) {
		fmt.Println ("Response error");
		fmt.Println (err)
	}
}

func response_server_file (con *net.TCPConn, path string) {
	fp, err := os.Open (path)
	defer fp.Close ()
	if (fp == nil || err != nil) {
		fmt.Println ("Open file fail")
		fmt.Println (path)
		fmt.Println (err)
		response_not_found (con)
		return
	}

	response_header (con)
	response_stream (con, fp)
}

func response_stream (con *net.TCPConn, fp *os.File) {
	var b [1024]byte
	var ret int
	var err error
	for {
		ret, err = fp.Read (b[:])
		if (ret == 0 || err != nil) {
			return
		}
		ret, err = con.Write (b[:ret])
		if (ret == 0 || err != nil) {
			fmt.Println ("Response error");
			fmt.Println (err)
		}
	}
}

func response_ok (con *net.TCPConn) {
	s := "HTTP/1.0 200 OK\r\n"
	do_response (con, &s)
}

func response_bad_request (con *net.TCPConn) {
	s := "HTTP/1.0 400 BAD REQUEST\r\nContent-type: text/html\r\n\r\n<P>Your browser sent a bad request, such as a POST without a Content-Length.\r\n"
	do_response (con, &s)
}

func response_header (con *net.TCPConn) {
	s := "HTTP/1.0 200 OK\r\nServer: gohttpd/0.1.0\r\nContent-Type: text/html\r\n\r\n"
	do_response (con, &s)
}

func response_not_found (con *net.TCPConn) {
	s := "HTTP/1.0 404 NOT FOUND\r\nContent-Type: text/html\r\n\r\n<HTML><TITLE>Not Found</TITLE>\r\n<BODY><P>The server could not fulfill\r\nyour request because the resource specified\r\nis unavailable or nonexistent.\r\n</BODY></HTML>\r\n"
	do_response (con, &s)
}

func response_unimplement (con *net.TCPConn) {
	s := "HTTP/1.0 501 Method Not Implemented\r\nContent-Type: text/html\r\n<HTML><HEAD><TITLE>Method Not Implemented\r\n</TITLE></HEAD>\r\n<BODY><P>HTTP request method not supported.\r\n</BODY></HTML>\r\n"
	do_response (con, &s)
}
